package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.common.RedisConst;
import com.itheima.health.entity.Result;
import com.itheima.health.util.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundValueOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * 验证码Controller
 */
@RestController
@RequestMapping("/mobile/validateCode")
@Slf4j
public class MobileValidateCodeController {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送验证码
     *
     * @param type      验证码类型
     * @param telephone 手机号
     */
    @PostMapping("/send")
    public Result sendCode(String type, String telephone) {
        log.info("验证码类型 ===> {}", type);
        //创建验证码字符串
        String code = null;
        //登录发送的验证码
        if (type.equals("MOBILE_SIGNIN")) {
            //登录操作生成6位验证码
            code = ValidateCodeUtils.generateValidateCode(6).toString();
            log.info("生成的登录验证码为 ===> {}", code);
        }
        //预约体检的验证码
        if (type.equals("ORDER")) {
            //预约体检生成4位验证码
            code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("生成体检预约验证码为 ===> {}", code);
        }
        BoundValueOperations ops = redisTemplate.boundValueOps(RedisConst.VALIDATE_CODE_PREFIX + telephone);
        //删除原有验证码
        if (ops!=null){
            redisTemplate.delete(RedisConst.VALIDATE_CODE_PREFIX + telephone);
        }
        //把验证码存储到Redis中,存活时间2分钟
        ops.set(code,2,TimeUnit.MINUTES);
        //返回结果
        return new Result(true, MessageConst.SEND_VALIDATECODE_SUCCESS);
    }

}
